<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="cartInfo in cartInfoList"
          :key="cartInfo.id"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              :checked="!!cartInfo.isChecked"
              @change="checkCartInfoState(cartInfo)"
              name="chk_list"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl" />
            <div class="item-msg">{{ cartInfo.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="changeskuNum('decrease',cartInfo)">-</a>
            <input
              autocomplete="off"
              type="text"
              :value="cartInfo.skuNum"
              minnum="1"
              class="itxt"
              @change="changeskuNum('change',cartInfo,$event)"
            />
            <a href="javascript:void(0)" class="plus" @click="changeskuNum('increase',cartInfo)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="#none"
              class="sindelet"
              @click="showDialogByDelOneCartInfo(cartInfo.skuId)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="#none" @click="deleteCheckedMany">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择 <span>{{selectCount}}</span>件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{selectMoney}}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade" >结算</router-link>
        </div>
      </div>
    </div>

    <!-- 使用对话框组件 -->
    <Dialog :visible.sync="visible">
      <template v-slot:header>
        <h3>提示</h3>
      </template>
      <template>
        <p>你真的要删除商品吗</p>
      </template>
      <template v-slot:footer>
        <div class="btn-footer">
          <button class="btn" @click="visible = false">取消</button>
          <button class="btn btn-primary" @click="deletedCartInfo">确定</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqGetCartListData,
  reqCheckedData,
  reqUpdateAllSkuInfoState,
  reqDeleteCart,
  reqDeleteChecked,
  reqAddShopCart
} from "@/api";
import Reg from '@/util/reg'
export default {
  name: "ShopCart",
  data() {
    return {
      cartInfoList: [],
      visible: false,
      isDelOne: false, // 是否删除一条数据
      skuIdList: [], // 批量删除数据时的数组
      leftCartInfoList: [], // 剩余的没有被删除的数据
      timId:0,
      num:0
    };
  },
  computed: {
    //全选与取消全选
    checkAll: {
      get() {
        return this.cartInfoList.every((item) => item.isChecked === 1);
      },
      async set(val) {
        // 当总按钮被选中的时候，则所有的小按钮也要被选中
        let isChecked = val ? 1 : 0;

        // 批量更新商品的选中状态
        let skuIdList = [];
        this.cartInfoList.forEach((item) => {
          item.isChecked = isChecked;
          skuIdList.push(item.skuId);
        });

        // 发送请求批量更新
        const res = await reqUpdateAllSkuInfoState(isChecked, skuIdList);
        if (res.code === 200) {
          alert("批量更新成功...");
        }
      },
    },
    //统计选中的数量
    selectCount(){
      return this.cartInfoList.reduce((prev,item) =>prev + item.isChecked,0 )
    },
    //统计总价格
    selectMoney(){
      return this.cartInfoList.reduce((prev,item)=>prev + item.skuPrice * item.skuNum * item.isChecked, 0)
    }
  },
  methods: {
    // 1.获取购物车的数据
    async getShopCartListData() {
      const res = await reqGetCartListData();
      if (res.code === 200) {
        // console.log(res);
        this.cartInfoList = res.data[0].cartInfoList;
      } else {
        console.log(res.message);
      }
    },
    // 2.选中与取消选中
    async checkCartInfoState(cartInfo) {
      let isChecked = 1 - cartInfo.isChecked;
      const result = await reqCheckedData(cartInfo.skuId, isChecked);
      // 可以少发一次请求 直接让页面按钮变成另一种状态--更新服务器数据成功后，重新更新页面
      cartInfo.isChecked = isChecked;
    },
    // 3点击删除按钮显示模态框，
    showDialogByDelOneCartInfo(skuId) {
      this.skuId = skuId;
      this.visible = true;
      //区分是一条还是多条
      this.isDelOne = true;
    },
    // 4.点击确认按钮，判断删除一条或者多条
    async deletedCartInfo() {
      // 4.1根据 isDelOne判断删除一条还是多条
      if (this.isDelOne) {
        const res = await reqDeleteCart(this.skuId);
        if (res.code === 200) {
          this.visible = false; //隐藏对话框
          this.cartInfoList = this.cartInfoList.filter(
            (item) => item.skuId != this.skuId
          );
        }
        return; //不在向下执行
      }
      // 4.2删除多条数据
      const res = await reqDeleteChecked(this.skuIdList);
      console.log(res);
      if (res.code === 200) {
        // 关闭弹框
        this.visible = false;

        //使用剩余的数据来渲染页面
        this.cartInfoList = this.leftCartInfoList;
      }
    },
    // 5.点击批量删除
    deleteCheckedMany() {
      this.skuIdList = [];
      this.leftCartInfoList = [];
      // 5.1弹出模态框
      this.visible = true;
      // 5.2判断是否删除多条数据
      this.isDelOne = false;
      // 5.3收集待删除的商品skuId
      this.cartInfoList.forEach((item) => {
        if (item.isChecked === 1) {
          //将需要删除的存入这个数组
          this.skuIdList.push(item.skuId);
        } else {
          // 将不需要删除的存入数组
          this.leftCartInfoList.push(item);
        }
      });
    },
    // 6.更改商品数量
   async changeskuNum(type,cartInfo,event){
      // let num = 0;
      //可以使用switch-case来处理数据
      switch(type){
        // 减少数量
        case 'decrease':
          if(cartInfo.skuNum > 1){
            cartInfo.skuNum--;
            // num--
            this.num--
          }
          break;
        //增加数量
        case 'increase':
          if(cartInfo.skuNum < 200){
            cartInfo.skuNum ++;
            // num++
            this.num++
          }
          break;
        case 'change':
          // 直接更改数量
          let newValue = event.target.value;
          let oldValue = cartInfo.skuNum;
          if(Reg.skuNumReg.test(newValue)){
            // 验证通过说明是文字
           cartInfo.skuNum = event.target.value - 0  //用户输入的类型都是字符串类型，转化成数字类型
             this.num = cartInfo.skuNum - oldValue;
             if(cartInfo.skuNum > 200){
                 cartInfo.skuNum = 200;
                 this.num = 200 - oldValue;
             }
          }
         else{
           // 否则就是非数字或是非法值  让skuNum还等于原值
            // 赋原值是赋值不上的 赋值不成功
            // cartInfo.skuNum = oldValue

            // 只能通过此种方式来进行赋值
            event.target.value = oldValue  // 是让页面中看起来的数据和原来还是一样的
        }
          break;
      }
      // if(num === 0) return  //不在发送请求
      if(this.num === 0) return  //不在发送请求
      // 最后将更改后的数据发送给服务器 是更改后的差值数据 不是显示出来的数据
      // await reqAddShopCart(cartInfo.skuId,num)   
      if(this.timId) clearTimeout(this.timId)
      this.timId = setTimeout(async ()=>{
        const res = await reqAddShopCart(cartInfo.skuId,this.num)
        if(res.code === 200){
          this.message({
            message:'数据更新成功',
            type:'success'
          })
        }else{
          this.message({
            message:'数据更新失败了...',
            type:'error'
          })
        }
        this.num = 0;  //一定要把num重置0
      },500)
    }
  },
  mounted() {
    this.getShopCartListData();
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
.btn-footer {
  position: absolute;
  right: 0px;
  bottom: 20px;
  .btn {
    width: 60px;
    height: 30px;
    border: 1px solid #ccc;
    margin: 0 10px;
    &.btn-primary {
      background-color: skyblue;
    }
  }
}
</style>